﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// .net core处理请求类
    /// </summary>
    public class ControllersHelper
    {

        /// <summary>
        /// 根据表名创建Controllers类
        /// </summary>
        /// <param name="strFilePath"></param>
        /// <param name="strProjectName"></param>
        /// <param name="strTableName"></param>
        /// <param name="strTableComment">已过滤的表注释</param>
        /// <param name="strComment">没有过滤的表注释</param>
        /// <param name="strDBName"></param>
        public static void CreateControllersClass(string strFilePath, string strProjectName, string strTableName, string strTableComment, string strComment, string strDBName)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");

            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);

            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes

            string strSwitchColumnName = GetSwitchColumnName(strDBName, strTableName);
            string strSwitchColumnNameText = GetSwitchColumnNameText(strDBName, strTableName);
            string strFormatSwitchColumnName = strSwitchColumnName.Replace("is_","");
            strFormatSwitchColumnName = CommonHelper.GetTableNameFirstUpper(strFormatSwitchColumnName);
            string strSortColumnName = CommonHelper.GetSortColumnName(strDBName, strTableName);

            string strGetCheckValue = CommonHelper.GetCheckValue(strTableName);
            if (string.IsNullOrEmpty(strGetCheckValue))
            {
                strGetCheckValue = strPrimaryKey;
            }

            Directory.CreateDirectory(strFilePath);
            StreamWriter sw = new StreamWriter(strFilePath + "\\" + strClassName + "Controller.cs", false, Encoding.GetEncoding("utf-8"));
            sw.WriteLine("using System;");
            sw.WriteLine("using System.Linq;");
            sw.WriteLine("using System.Threading.Tasks;");
            sw.WriteLine("using Microsoft.AspNetCore.Mvc;");
            sw.WriteLine("using Microsoft.EntityFrameworkCore;");
            // sw.WriteLine("using System.Collections.Generic;");
            sw.WriteLine("using " + strProjectName + ".Manage.Data;");
            sw.WriteLine("using " + strProjectName + ".Models;");
            sw.WriteLine("using " + strProjectName + ".Utility.Helper;");
            sw.WriteLine("using " + strProjectName + ".Manage.Filters;");
            // sw.WriteLine("using Microsoft.AspNetCore.Http;");
            sw.WriteLine("using Senparc.CO2NET.Extensions;");
            sw.WriteLine("using Microsoft.AspNetCore.Authorization;");
            sw.WriteLine("using System.Security.Claims;");
            sw.WriteLine("");
            sw.WriteLine("namespace " + strProjectName + ".Manage.Controllers");
            sw.WriteLine("{");
            sw.WriteLine("");
            sw.WriteLine("    /// <summary>");
            sw.WriteLine("    /// 版权所有: Copyright © " + DateTime.Now.Year.ToString() + " " + strCompany + ". 保留所有权利。");
            sw.WriteLine("    /// 内容摘要: " + strClassName + " 处理请求的类");
            sw.WriteLine("    /// 创建日期：" + Convert.ToDateTime(strCreateDate).ToString("yyyy年M月d日"));
            sw.WriteLine("    /// 更新日期：" + DateTime.Now.ToString("yyyy年M月d日"));
            sw.WriteLine("    /// 版    本：V" + strVersion + "." + strCode + " ");
            sw.WriteLine("    /// 作    者：" + strAuthor);
            sw.WriteLine("    /// </summary>");
            sw.WriteLine("    [Authorize]");
            sw.WriteLine("    public class " + strClassName + "Controller : BaseController<" + strClassName + "Controller>");
            sw.WriteLine("    {");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// " + strTableComment + " 实例化数据上下文");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"context\"></param>");
            sw.WriteLine("        public " + strClassName + "Controller(" + strProjectName + "ManageContext context) : base(context)");
            sw.WriteLine("        {");
            sw.WriteLine("");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 管理/列表页面");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <returns></returns>");
            sw.WriteLine("        public IActionResult Index()");
            sw.WriteLine("        {");
            sw.WriteLine("            return View();");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 新增页面");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <returns></returns>");
            sw.WriteLine("        public IActionResult Create()");
            sw.WriteLine("        {");
            sw.WriteLine("            return View();");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 编辑页面");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <returns></returns>");
            sw.WriteLine("        public IActionResult Edit()");
            sw.WriteLine("        {");
            sw.WriteLine("            return View();");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 详情页面");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <returns></returns>");
            sw.WriteLine("        public IActionResult Views()");
            sw.WriteLine("        {");
            sw.WriteLine("            return View();");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 获取" + strTableComment + "列表数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"page\">页码</param>");
            sw.WriteLine("        /// <param name=\"limit\">每页显示数量</param>");
            sw.WriteLine("        /// <param name=\"created_at\">创建日期</param>");
            sw.WriteLine(GetSearchColumnComments(strDBName,strTableName));
            sw.WriteLine("        /// <returns>返回" + strTableComment + "JSON数据集合</returns>");
            //sw.WriteLine("        // GET: " + strTableNameLower + "/lists/?page=1&limit=10");
            sw.WriteLine("        public async Task<IActionResult> List(int page, int limit, string created_at"+ GetSearchColumn(strDBName,strTableName)+ ")");
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            if (!string.IsNullOrEmpty(CommonHelper.GetDetailsSelectJoinList(strDBName, strTableName)))
            {
                sw.WriteLine("                var result = from item in _context.Set<" + strClassName + ">()");
                // sw.WriteLine("                             " + CommonHelper.GetDetailsSelectJoinList(strDBName, strTableName));
                sw.WriteLine("                             select new");
                sw.WriteLine("                             {");
                sw.WriteLine(CommonHelper.GetLeftSelectColumnName2(strProjectName, strDBName, strTableName, "item"));
                // sw.WriteLine(CommonHelper.GetDetailsSelectJoinColumn(strDBName, strTableName, strPrimaryKey, CommonHelper.GetLeftSelectColumnName2(strProjectName, strDBName, strTableName, "item")));
                sw.WriteLine("                             };");
                sw.WriteLine("");
                sw.WriteLine(GetSearchWhere(strDBName,strTableName));
                if (CommonHelper.ChecktCreatedAtKey(strTableName, "created_at"))
                {
                    sw.WriteLine("                if (!string.IsNullOrEmpty(created_at))");
                    sw.WriteLine("                {");
                    sw.WriteLine("                    created_at = created_at.Replace(\" - \", \",\");");
                    sw.WriteLine("                    string[] splitDate = created_at.Split(new char[] { ',' });");
                    sw.WriteLine("                    string start_at = splitDate[0];");
                    sw.WriteLine("                    string end_at = splitDate[1];");
                    sw.WriteLine("                    result = result.Where(t => t.created_at >= Convert.ToDateTime(start_at) && t.created_at <= Convert.ToDateTime(end_at).AddDays(1));");
                    sw.WriteLine("                }");
                    sw.WriteLine("");
                    sw.WriteLine("                var list = await result.OrderByDescending(t => t.created_at).Skip((page - 1) * limit).Take(limit).ToListAsync();");
                }
                else
                {
                    sw.WriteLine("                var list = await result.OrderByDescending(t => t." + strPrimaryKey + ").Skip((page - 1) * limit).Take(limit).ToListAsync();");
                }

                sw.WriteLine("                var lCount = result.LongCount();");
                sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.List + \"\" + (int)ENUMHelper.InfoType.Info, \"查询" + strTableComment + "LINQ=\" + result.Expression.ToString() + \",DATA=\" + list.ToJson());");
                sw.WriteLine("                if (lCount <= 0)");
                sw.WriteLine("                {");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"暂无数据\", count = 0 });");
                sw.WriteLine("                }");
                sw.WriteLine("                else");
                sw.WriteLine("                {");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"success\", data = list, count = lCount });");
                sw.WriteLine("                }");
            }
            else
            {
                sw.WriteLine("                var result = from item in _context.Set<" + strClassName + ">()");
                sw.WriteLine("                             select new");
                sw.WriteLine("                             {");
                sw.WriteLine(CommonHelper.GetLeftSelectColumnName2(strProjectName, strDBName, strTableName, "item"));
                sw.WriteLine("                              };");
                sw.WriteLine("");
                sw.WriteLine(GetSearchWhere(strDBName, strTableName));
                if (CommonHelper.ChecktCreatedAtKey(strTableName, "created_at"))
                {
                    sw.WriteLine("                if (!string.IsNullOrEmpty(created_at))");
                    sw.WriteLine("                {");
                    sw.WriteLine("                    created_at = created_at.Replace(\" - \", \",\");");
                    sw.WriteLine("                    string[] splitDate = created_at.Split(new char[] { ',' });");
                    sw.WriteLine("                    string start_at = splitDate[0];");
                    sw.WriteLine("                    string end_at = splitDate[1];");
                    sw.WriteLine("                    result = result.Where(t => t.created_at >= Convert.ToDateTime(start_at) && t.created_at <= Convert.ToDateTime(end_at).AddDays(1));");
                    sw.WriteLine("                }");
                    sw.WriteLine("");
                }
                sw.WriteLine("                var list =  await result.OrderByDescending(t => t." + strPrimaryKey + ").Skip((page - 1) * limit).Take(limit).ToListAsync();");
                sw.WriteLine("                var lCount = result.LongCount();");
                sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.List + \"\" + (int)ENUMHelper.InfoType.Info, \"查询" + strTableComment + "LINQ=\" + result.Expression.ToString() + \",DATA=\" + list.ToJson());");
                sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = list, count = lCount });");
            }

            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> List\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.List, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 获取" + strTableComment + "数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <returns>返回" + strTableComment + "JSON数据集合</returns>");
            //sw.WriteLine("        // GET: " + strTableNameLower + "/select");
            sw.WriteLine("        public async Task<IActionResult> Select()");
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                var list = await _context." + strTableName + ".OrderBy(t => t." + strPrimaryKey + ").ToListAsync();");
            sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Select + \"\" + (int)ENUMHelper.InfoType.Info, \"查询" + strTableComment + "下拉填充,DATA=\" + list.ToJson());");
            sw.WriteLine("");
            sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = list });");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Select\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Select, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 根据ID获取" + strTableComment + "详情");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
            sw.WriteLine("        /// <returns>返回单条" + strTableComment + "JSON数据</returns>");
            sw.WriteLine("        [HttpGet(\"/"+ strClassName.ToLower() + "/details\")]");
            if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            {
                sw.WriteLine("        public async Task<IActionResult> Details(long id)");
            }
            else
            {
                sw.WriteLine("        public async Task<IActionResult> Details(int id)");
            }
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Information(\"id=\" + id);");
            sw.WriteLine("                var result = await _context." + strTableName + ".Where(t => t." + strPrimaryKey + " == id).Select(item => (new");
            sw.WriteLine("                {");
            sw.WriteLine(CommonHelper.GetLeftSelectColumnName3(strProjectName, strDBName, strTableName, "item"));
            sw.WriteLine("                })).FirstOrDefaultAsync();");
            sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Search, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Details + \"\" + (int)ENUMHelper.InfoType.Info, \"获取" + strTableComment + "详情ID=\" + id + \",result=\" + result.ToJson());");
            sw.WriteLine("                if (result == null)");
            sw.WriteLine("                {");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"数据为空\", count = 0 });");
            sw.WriteLine("                }");
            sw.WriteLine("                else");
            sw.WriteLine("                {");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"success\", data = result });");
            sw.WriteLine("                }");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Details\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Details, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            //sw.WriteLine("        /// <summary>");
            //sw.WriteLine("        /// 根据ID获取" + strTableComment + "详情数据");
            //sw.WriteLine("        /// </summary>");
            //sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
            //sw.WriteLine("        /// <returns>返回单条" + strTableComment + "JSON数据</returns>");
            ////sw.WriteLine("        // GET: " + strTableNameLower + "/details/1");
            //if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            //{
            //    sw.WriteLine("        public IActionResult Details(long? id)");
            //}
            //else
            //{
            //    sw.WriteLine("        public IActionResult Details(int? id)");
            //}

            //sw.WriteLine("        {");
            //sw.WriteLine("            try");
            //sw.WriteLine("            {");
            //sw.WriteLine("                log.Information(\"id=\" + id);");
            //sw.WriteLine("                var result = _context."+ strTableName + ".Where(t => t." + strPrimaryKey + " == id).Select(item => (new");
            //sw.WriteLine("                {");
            //sw.WriteLine(CommonHelper.GetLeftSelectColumnName3(strProjectName, strDBName, strTableName, "item"));
            //sw.WriteLine("                })).FirstOrDefault();");
            //sw.WriteLine("                AddLogs(7, \"获取详情ID=\" + id + \",result=\" + result.ToJson(), \"BP75000\");");
            //sw.WriteLine("                if (result == null)");
            //sw.WriteLine("                {");
            //sw.WriteLine("                    return Json(new { code = 0, msg = \"数据为空\", count = 0 });");
            //sw.WriteLine("                }");
            //sw.WriteLine("                else");
            //sw.WriteLine("                {");
            //sw.WriteLine("                    return Json(new { code = 0, msg = \"success\", data = result });");
            //sw.WriteLine("                }");
            //sw.WriteLine("            }");
            //sw.WriteLine("            catch (Exception ex)");
            //sw.WriteLine("            {");
            //sw.WriteLine("                log.Fatal(ex, \" -> Details\");");
            //sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Details, errmsg = ex.Message });");
            //sw.WriteLine("            }");
            //sw.WriteLine("        }");
            //sw.WriteLine("");
            if (strComment.Contains("{MutiPages}"))
            {
                sw.WriteLine("        /// <summary>");
                sw.WriteLine("        /// 按天统计" + strTableComment + "数据");
                sw.WriteLine("        /// </summary>");
                sw.WriteLine("        /// <returns>返回每日统计" + strTableComment + "JSON数据集合</returns>");
                sw.WriteLine("        public async Task<IActionResult> ChartByDay()");
                sw.WriteLine("        {");
                sw.WriteLine("            try");
                sw.WriteLine("            {");
                // sw.WriteLine("                // money = g.Sum(t => t.total_pay)");
                sw.WriteLine("                var list = await _context." + strTableName + ".GroupBy(t => new { t.created_at.Year, t.created_at.Month, t.created_at.Day }).Select(g => (new { year = g.Key.Year, month = g.Key.Month, day = g.Key.Day, count = g.Count() })).OrderBy(t => t.year).ThenBy(t => t.month).ThenBy(t => t.day).ToListAsync();");
                sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Count, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Chart + \"\" + (int)ENUMHelper.InfoType.Info,\"查询" + strTableComment + "统计数据,list=\" + list.ToJson());");
                sw.WriteLine("                return Json(new { code = 0, msg = \"success\", data = list });");
                sw.WriteLine("            }");
                sw.WriteLine("            catch (Exception ex)");
                sw.WriteLine("            {");
                sw.WriteLine("                log.Fatal(ex, \" -> ChartByDay\");");
                sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Chart, errmsg = ex.Message });");
                sw.WriteLine("            }");
                sw.WriteLine("        }");
                sw.WriteLine("");
            }
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 新增" + strTableComment + "数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"" + strTableNameSpec + "\">" + strClassName + "对象</param>");
            sw.WriteLine("        /// <returns>返回新增" + strTableComment + "后的单条JSON数据</returns>");
            // sw.WriteLine("        // POST: " + strTableNameLower + "/create");
            sw.WriteLine("        [HttpPost]");
            sw.WriteLine("        [ValidateAntiForgeryToken]");
            sw.WriteLine("        public async Task<IActionResult> Create(" + strClassName + " " + strTableNameSpec + ")");
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            // sw.WriteLine("                log.Information(" + CommonHelper.GetSaveLogColumnName(strTableName, strTableNameSpec) + ");");
            sw.WriteLine("                log.Information(" + '"' + strTableNameSpec + '=' + '"' + " + " + strTableNameSpec + ".ToJson()" + ");");
            if (CommonHelper.ChecktCreatedAtKey(strTableName, "user_id"))
            {
                sw.WriteLine("                " + strTableNameSpec + ".user_id = GetUserID();");
            }
            if (CommonHelper.ChecktCreatedAtKey(strTableName, "created_at"))
            {
                sw.WriteLine("                " + strTableNameSpec + ".created_at = DateTime.Now;");
            }
            // sw.WriteLine("                // _context." + strTableName + ".Add(" + strTableNameSpec + ");");
            sw.WriteLine("                if (!_context." + strTableName + ".Any(t => t."+ strGetCheckValue + "!.Equals(" + strTableNameSpec + "." + strGetCheckValue + ")))");
            sw.WriteLine("                {");
            sw.WriteLine("                    _context." + strTableName + ".Add(" + strTableNameSpec + ");");
            sw.WriteLine("                    // await _context.SaveChangesAsync();");
            sw.WriteLine("                    AddLogs((int)ENUMHelper.LogType.Create, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Create + \"\" + (int)ENUMHelper.InfoType.Info, \"新增" + strTableComment + "," + strTableNameSpec + "=\" + " + strTableNameSpec + ".ToJson());");
            sw.WriteLine("");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"添加成功\", data = " + strTableNameSpec + " });");
            sw.WriteLine("                }");
            sw.WriteLine("                else");
            sw.WriteLine("                {");
            sw.WriteLine("                    return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = \"添加失败，请不要重复添加！\"});");
            sw.WriteLine("                }");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Create\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 根据ID更改" + strTableComment + "数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
            sw.WriteLine("        /// <param name=\"" + strTableNameSpec + "\">" + strClassName + "对象</param>");
            sw.WriteLine("        /// <returns>返回修改" + strTableComment + "后的单条JSON数据</returns>");
            // sw.WriteLine("        // POST: " + strTableNameLower + "/edit/1");
            sw.WriteLine("        [HttpPost]");
            sw.WriteLine("        [ValidateAntiForgeryToken]");
            if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            {
                sw.WriteLine("        public async Task<IActionResult> Edit(long id, " + strClassName + " " + strTableNameSpec + ")");
            }
            else
            {
                sw.WriteLine("        public async Task<IActionResult> Edit(int id, " + strClassName + " " + strTableNameSpec + ")");
            }

            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            //sw.WriteLine("                log.Information(" + CommonHelper.GetSaveLogColumnName(strTableName, strTableNameSpec) + ");");
            sw.WriteLine("                log.Information(" + '"' + strTableNameSpec + '=' + '"' + " + " + strTableNameSpec + ".ToJson()" + ");");
            sw.WriteLine("                var item = _context." + strTableName + ".Find(id);");
            sw.WriteLine("                if (item != null)");
            sw.WriteLine("                {");
            sw.WriteLine(CommonHelper.GetUpdateItems(strDBName, strTableNameSpec, strTableName));
            sw.WriteLine("                    _context." + strTableName + ".Update(item);");
            sw.WriteLine("                    // await _context.SaveChangesAsync();");
            sw.WriteLine("                    AddLogs((int)ENUMHelper.LogType.Update, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Edit + \"\" + (int)ENUMHelper.InfoType.Info, \"编辑" + strTableComment + "ID=\" + id+ \"," + strTableNameSpec + "=\" + " + strTableNameSpec + ".ToJson());");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"更新成功\", data = item });");
            sw.WriteLine("                }");
            sw.WriteLine("                else");
            sw.WriteLine("                {");
            sw.WriteLine("                   return Json(new { code = 0, msg = \"操作失败，ID=\" + id + \"不存在！\"});");
            sw.WriteLine("                }");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Edit\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Edit, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            // 处理开关字段
            if (!string.IsNullOrEmpty(strSwitchColumnName))
            {

                sw.WriteLine("        /// <summary>");
                sw.WriteLine("        /// 更新" + strSwitchColumnNameText + "状态");
                sw.WriteLine("        /// </summary>");
                sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
                sw.WriteLine("        /// <param name=\"status\">" + strSwitchColumnNameText + "</param>");
                sw.WriteLine("        /// <returns>返回更新" + strSwitchColumnNameText + "后的单条JSON数据</returns>");
                sw.WriteLine("        [HttpPost]");
                sw.WriteLine("        [ValidateAntiForgeryToken]");
                sw.WriteLine("        public async Task<IActionResult> Set" + strFormatSwitchColumnName + "(long id, bool status)");
                sw.WriteLine("        {");
                sw.WriteLine("            try");
                sw.WriteLine("            {");
                sw.WriteLine("                log.Information(\"id=\" + id + \",status=\" + status);");
                sw.WriteLine("                var item = await _context." + strTableName + ".FirstOrDefaultAsync(t => t." + strPrimaryKey + " == id);");
                sw.WriteLine("                if (item != null)");
                sw.WriteLine("                {");
                sw.WriteLine("                    item." + strSwitchColumnName + " = status;");
                sw.WriteLine("                    _context." + strTableName + ".Update(item);");
                sw.WriteLine("                    await _context.SaveChangesAsync();");
                sw.WriteLine("                    AddLogs((int)ENUMHelper.LogType.Update, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Edit + \"\" + (int)ENUMHelper.InfoType.Info, \"更新" + strTableComment + "ID=\" + id);");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"更新成功\", data = item });");
                sw.WriteLine("                }");
                sw.WriteLine("                else");
                sw.WriteLine("                {");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"操作失败，ID=\" + id + \"不存在！\"});");
                sw.WriteLine("                }");
                sw.WriteLine("            }");
                sw.WriteLine("            catch (Exception ex)");
                sw.WriteLine("            {");
                sw.WriteLine("                log.Fatal(ex, \" -> Set" + strFormatSwitchColumnName + "\");");
                sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Edit, errmsg = ex.Message });");
                sw.WriteLine("            }");
                sw.WriteLine("        }");
                sw.WriteLine("");
            }
            // 处理排序字段
            if (!string.IsNullOrEmpty(strSortColumnName))
            {

                sw.WriteLine("        /// <summary>");
                sw.WriteLine("        /// 设置排序");
                sw.WriteLine("        /// </summary>");
                sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
                sw.WriteLine("        /// <param name=\"sort\">排序</param>");
                sw.WriteLine("        /// <returns>返回设置排序后的单条JSON数据</returns>");
                sw.WriteLine("        [HttpPost]");
                sw.WriteLine("        [ValidateAntiForgeryToken]");
                sw.WriteLine("        public async Task<IActionResult> SetSort(long id, int sort)");
                sw.WriteLine("        {");
                sw.WriteLine("            try");
                sw.WriteLine("            {");
                sw.WriteLine("                log.Information(\"id=\" + id + \",sort=\" + sort);");
                sw.WriteLine("                var item = await _context." + strTableName + ".FirstOrDefaultAsync(t => t." + strPrimaryKey + " == id);");
                sw.WriteLine("                if (item != null)");
                sw.WriteLine("                {");
                sw.WriteLine("                    item.sort_num = sort;");
                sw.WriteLine("                    _context." + strTableName + ".Update(item);");
                sw.WriteLine("                    await _context.SaveChangesAsync();");
                sw.WriteLine("                    AddLogs((int)ENUMHelper.LogType.Update, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Edit + \"\" + (int)ENUMHelper.InfoType.Info, \"设置" + strTableComment + "ID=\" + id);");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"设置成功\", data = item });");
                sw.WriteLine("                }");
                sw.WriteLine("                else");
                sw.WriteLine("                {");
                sw.WriteLine("                    return Json(new { code = 0, msg = \"操作失败，ID=\" + id + \"不存在！\"});");
                sw.WriteLine("                }");
                sw.WriteLine("            }");
                sw.WriteLine("            catch (Exception ex)");
                sw.WriteLine("            {");
                sw.WriteLine("                log.Fatal(ex, \" -> SetSort\");");
                sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Edit, errmsg = ex.Message });");
                sw.WriteLine("            }");
                sw.WriteLine("        }");
                sw.WriteLine("");
            }
            sw.WriteLine("        /// <summary>");
            sw.WriteLine("        /// 根据ID删除" + strTableComment + "数据");
            sw.WriteLine("        /// </summary>");
            sw.WriteLine("        /// <param name=\"id\">" + strTableComment + "ID</param>");
            sw.WriteLine("        /// <returns>返回删除操作信息</returns>");
            // sw.WriteLine("        // POST: " + strTableNameLower + "/delete/1");
            sw.WriteLine("        [HttpPost]");
            sw.WriteLine("        [ValidateAntiForgeryToken]");
            if (CommonHelper.ChecktKeyIsBigint(strTableName, strPrimaryKey))
            {
                sw.WriteLine("        public async Task<IActionResult> Delete(long id)");
            }
            else
            {
                sw.WriteLine("        public async Task<IActionResult> Delete(int id)");
            }
            sw.WriteLine("        {");
            sw.WriteLine("            try");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Information(\"id=\" + id);");
            sw.WriteLine("                var item = _context." + strTableName + ".Find(id);");
            sw.WriteLine("                if (item == null)");
            sw.WriteLine("                {");
            sw.WriteLine("                    return Json(new { code = 0, msg = \"操作失败，ID=\" + id + \"不存在！\" });");
            sw.WriteLine("                }");
            sw.WriteLine("                // _context." + strTableName + ".Remove(item);");
            sw.WriteLine("                await _context.SaveChangesAsync();");
            sw.WriteLine("                AddLogs((int)ENUMHelper.LogType.Delete, (int)ENUMHelper.Platform.Admin + \"\" + (int)ENUMHelper.OperateType.Logout + \"\" + (int)ENUMHelper.InfoType.Info,  \"删除" + strTableComment + "ID=\" + id + \",item=\" + item.ToJson());");
            sw.WriteLine("");
            sw.WriteLine("                return Json(new { code = 0, msg = \"删除成功\" });");
            sw.WriteLine("            }");
            sw.WriteLine("            catch (Exception ex)");
            sw.WriteLine("            {");
            sw.WriteLine("                log.Fatal(ex, \" -> Delete\");");
            sw.WriteLine("                return Json(new { code = 0, errcode = (int)ENUMHelper.ExceptionType.Delete, errmsg = ex.Message });");
            sw.WriteLine("            }");
            sw.WriteLine("        }");
            sw.WriteLine("");
            sw.WriteLine("    }");
            sw.WriteLine("}");
            sw.Close();

        }

        /// <summary>
        /// 获取搜索字段注释
        /// </summary>
        /// <param name="strDBName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSearchColumnComments(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释
                    string strDataType = dr["DATA_TYPE"].ToString();//注释

                    if (strColumnComment.Contains("{搜索}"))
                    {
                        strColumnComment = CommonHelper.GetColumnKeyComment(strColumnComment);
                        string strValue = "        /// <param name=\"" + strColumnName + "\">" + strColumnComment + "</param>\r\n";
                        strReturnValue += strValue;
                    }
                }
                dr.Dispose();
                cn.Close();

                if (strReturnValue.Length> 0)
                {
                    strReturnValue = strReturnValue.Substring(0, strReturnValue.Length - 2);
                }
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段注释", "GetSearchColumnComments", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取搜索字段
        /// </summary>
        /// <param name="strDBName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSearchColumn(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释
                    string strDataType = dr["DATA_TYPE"].ToString();//注释

                    if (strColumnComment.Contains("{搜索}"))
                    {
                        string strValue = "";
                        if (strDataType == "int" || strDataType == "bigint" || strDataType == "smallint")
                        {
                            strValue = ", int " + strColumnName + " = -1";
                        }
                        else if (strDataType == "decimal")
                        {
                            strValue = ", decimal " + strColumnName;
                        }
                        else if (strDataType == "bit")
                        {
                            strValue = ", int " + strColumnName + " = -1";
                        }
                        else
                        {
                            strValue = ", string " + strColumnName;
                        }

                        strReturnValue += strValue;
                    }
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段", "GetSearchColumn", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取搜索条件
        /// </summary>
        /// <param name="strDBName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSearchWhere(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释
                    string strDataType = dr["DATA_TYPE"].ToString();//注释

                    if (strColumnComment.Contains("{搜索}"))
                    {
                        string strValue = "";
                        if (strDataType == "int" || strDataType == "bigint" || strDataType == "smallint")
                        {
                            strValue = "                if (" + strColumnName + " > 0)\r\n";
                            strValue += "                {\r\n";
                            strValue += "                   result = result.Where(t => t." + strColumnName + " == " + strColumnName + ");\r\n";
                            strValue += "                }\r\n";
                        }
                        else if (strDataType == "decimal")
                        {
                            strValue = "                if (" + strColumnName + " > 0)\r\n";
                            strValue += "                {\r\n";
                            strValue += "                   result = result.Where(t => t." + strColumnName + " == " + strColumnName + ");\r\n";
                            strValue += "                }\r\n";
                        }
                        else if (strDataType == "bit")
                        {
                            strValue = "                if (" + strColumnName + " > -1)\r\n";
                            strValue += "                {\r\n";
                            strValue += "                    if (" + strColumnName + " == 1)\r\n";
                            strValue += "                    {\r\n";
                            strValue += "                      result = result.Where(t => t." + strColumnName + " == true);\r\n";
                            strValue += "                    }\r\n";
                            strValue += "                    if (" + strColumnName + " == 0)\r\n";
                            strValue += "                    {\r\n";
                            strValue += "                      result = result.Where(t => t." + strColumnName + " == false);\r\n";
                            strValue += "                    }\r\n";
                            strValue += "                }\r\n";
                        }
                        else
                        {
                            strValue = "                if (!string.IsNullOrEmpty(" + strColumnName + "))\r\n";
                            strValue += "                {\r\n";
                            strValue += "                   result = result.Where(t => t." + strColumnName + ".Contains(" + strColumnName + ".Trim()));\r\n";
                            strValue += "                }\r\n";
                        }

                        strReturnValue += strValue;
                    }
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索条件", "GetSearchWhere", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取开关在列表支持动态更新字段
        /// </summary>
        /// <param name="strDBName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSwitchColumnName(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    if (strColumnComment.Contains("{开关}"))
                    {
                        strReturnValue = strColumnName;
                    }
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取上传图片字段", "GetImgColumnName", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取开关在列表支持动态更新字段
        /// </summary>
        /// <param name="strDBName"></param>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSwitchColumnNameText(string strDBName, string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='" + strDBName + "' AND TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    if (strColumnComment.Contains("{开关}"))
                    {
                        strColumnComment = CommonHelper.GetColumnKeyComment(strColumnComment);
                        strColumnComment = strColumnComment.Replace("1=", "");
                        strColumnComment = strColumnComment.Replace("0=", "");
                        strReturnValue = strColumnComment;
                    }
                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取上传图片字段", "GetImgColumnName", false);
            }

            return strReturnValue;

        }

    }
}
